#include "Scene/SceneNode.h"

#include "Framework/StableHeaders.h"
#include "Scene/ISceneManager.h"
#include "Geometry/Object.h"
#include "Scene/IRenderQueue.h"

namespace tyro
{
	namespace Scene
	{


		void SceneNode::AttachObject( Geometry::Object* obj )
		{

			obj->NotifyAttached(this);

			objectMap.insert(ObjectMap::value_type(obj->GetName(), obj));

		}

		SceneNode::SceneNode( ISceneManager* mgr,String name )
			:	Node(name)
			,	sceneManager(mgr)
		{
			FlagUpdate();
		}

		SceneNode::SceneNode( ISceneManager* mgr )
			:	Node()
			,	sceneManager(mgr)
		{
			FlagUpdate();
		}

		void SceneNode::Update()
		{
			Node::Update();
		}

		SceneNode* SceneNode::CreateChildSceneNode( const Math::Vector3f& translation /*= Math::Vector3f::ZERO*/, const Math::Quaternionf& rotation /*= Math::Quaternionf::IDENTITY*/ )
		{
			return static_cast<SceneNode*>(this->CreateChildNode(translation, rotation));
		}

		Node* SceneNode::CreateChildImpl(void)
		{
			return sceneManager->CreateSceneNode();
		}

		Node* SceneNode::CreateChildImpl( const String& name )
		{
			return sceneManager->CreateSceneNode(name);
		}

		void SceneNode::FindVisibleObjects( Camera::Camera* camera, IRenderQueue* renderQueue, bool includeChildren )
		{

			// Check to see if object is visible to the active camera

			// Add all objects to render que
			ObjectMap::iterator object, objectsEnd;
			objectsEnd = objectMap.end();
			for(object = objectMap.begin(); object != objectsEnd; ++object)
			{
				Geometry::Object* obj = object->second; 
				renderQueue->ProcessVisibleObject(obj, camera);
			}


			if (includeChildren)
			{
				// Add all child nodes to render que
				ChildNodeMap::iterator child, childEnd; 
				childEnd = children.end();
				for (child = children.begin(); child != childEnd; ++child)
				{
					SceneNode* childNode = static_cast<SceneNode*>(child->second);
					childNode->FindVisibleObjects(camera, renderQueue, includeChildren);
				}
			}

		}

	}
}